const createError = require('http-errors')
const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const logger = require('morgan')
// 引入 express-session 和 connect-mongo 模块
const session = require('express-session')
const MongoStore = require('connect-mongo')
const fs = require('fs')

// 导入配置项
const { DBHOST, DBNAME, DBPORT } = require('./config/config')

const cors = require('cors')

const app = express()

// 跨域白名单
const whitelist = ['http://172.16.15.36:6060', 'http://172.16.15.29:6060', 'http://192.168.36.1:6060', 'http://localhost:6060', 'http://127.0.0.1:5500']
// CORS 配置函数
const corsOptions = {
  origin: function (origin, callback) {
    // 允许白名单内的域名
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}
// 使用 CORS 中间件
app.use(cors(corsOptions))

// 初始化统一响应机制
app.use(require('./modules/resextra'))

app.use(
  logger('combined', {
    stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
  })
)

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

// 这里子路由需要放在 '/' 路由之前，有点奇怪
app.use('/api', require('./routes/api/avatar'))
app.use('/api', require('./routes/api/router'))
app.use('/api', require('./routes/api/auth'))
app.use('/api', require('./routes/api/account'))

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  // 响应 404
  res.sendResult(null, 404, 'Not Found')
})

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}
  res.status(err.status || 500)
  console.log(err)
  res.sendResult(null, 500, '服务器内部错误')
})

module.exports = app
